package com.lanou.bookstore.order.web.servlet;

import com.lanou.bookstore.book.domain.Book;
import com.lanou.bookstore.book.service.BookService;
import com.lanou.bookstore.cart.domain.Cart;
import com.lanou.bookstore.cart.domain.CartItem;
import com.lanou.bookstore.order.domain.Order;
import com.lanou.bookstore.order.domain.OrderItem;
import com.lanou.bookstore.order.service.OrderService;
import com.lanou.bookstore.user.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("/order")
public class OrderServlet extends HttpServlet {
    private OrderService orderService = new OrderService();
    private BookService bookService = new BookService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String address = request.getParameter("address");
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format(date);
        Cart carts = (Cart) request.getSession().getAttribute("carts");
        User user = (User) request.getSession().getAttribute("user");
        Map<String, CartItem> cartItems = carts.getCartItems();
        Set<String> keySet = cartItems.keySet();
        Iterator<String> iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            if (key != null) {
                CartItem cartItem = cartItems.get(key);
                Order order = new Order(null, format, cartItem.getBook().getPrice() * cartItem.getBcount(), null, user.getUid(), address);
                Integer lastOid = orderService.addOrder(order);
                OrderItem orderItem = new OrderItem(null, cartItem.getBcount(), cartItem.getBook().getPrice() * cartItem.getBcount(), lastOid, cartItem.getBook().getBid());
                orderService.addOrderItem(orderItem);
            }
        }
        request.getSession().removeAttribute("carts");
        request.getRequestDispatcher("/alipay.trade.page.pay.jsp").forward(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        String ordertime = request.getParameter("ordertime");
        String orderTime = request.getParameter("orderTime");
        if (user != null && ordertime == null && orderTime == null) {
            List<String> stringList = orderService.findOrderTimeByUid(user.getUid());
            Map map = new HashMap();
            for (String str : stringList) {
                List<Order> orderList = orderService.findOrderAllByOrderTime(str);
                Map<OrderItem, Book> orderItemBookMap = new HashMap<>();
                for (Order order : orderList) {
                    OrderItem orderItem = orderService.findOrderItemAllByOid(order.getOid());
                    Book book = bookService.findByBid(String.valueOf(orderItem.getBid()));
                    orderItemBookMap.put(orderItem, book);
                }
                map.put(str, orderItemBookMap);
            }

            request.setAttribute("maps", map);
            request.getRequestDispatcher("/jsps/order/list.jsp").forward(request, response);
        } else if (user != null && ordertime != null && orderTime == null) {
            List<Order> orderList = orderService.findOrderAllByOrderTime(ordertime);
            Map<String, CartItem> cartItems = new HashMap<>();
            for (Order order : orderList) {
                OrderItem orderItem = orderService.findOrderItemAllByOid(order.getOid());
                Book book = bookService.findByBid(String.valueOf(orderItem.getBid()));
                CartItem cartItem = new CartItem(book, orderItem.getCount());
                cartItems.put(book.getBname(), cartItem);
            }
            Cart cart = new Cart();
            cart.setCartItems(cartItems);
            request.setAttribute("carts", cart);
            request.getRequestDispatcher("/jsps/order/desc.jsp").forward(request, response);
        } else if (user != null && orderTime != null && ordertime == null) {
            List<Order> orderList = orderService.findOrderAllByOrderTime(orderTime);
            for (Order order : orderList) {
                //如果result = true ，证明state = 3，否则 state ！= 3；
                boolean result = orderService.findOrderStateByOid(order.getOid());
                if (!result) {
                    orderService.updateOrdersStateByOid(order.getOid());
                } else {
                    request.setAttribute("msg", "订单确认失败，你不是好人");
                    request.getRequestDispatcher("/jsps/order/msg.jsp").forward(request, response);
                }
            }
            request.setAttribute("msg", "确认成功，交易完成");
            request.getRequestDispatcher("/jsps/order/msg.jsp").forward(request, response);
        }

    }
}
